package cn.jbolt.wechat.util;

import cn.jbolt.core.api.JBoltApiKit;
import cn.jbolt.core.api.JBoltApiRet;
import cn.jbolt.core.model.Application;
import cn.jbolt.wechat.cache.JBoltWechatConfigCache;
import cn.jbolt.wechat.cache.JBoltWechatMpinfoCache;
import cn.jbolt.wechat.model.WechatMpinfo;
import com.jfinal.kit.StrKit;

import static cn.jbolt.core.para.JBoltParaValidator.notOk;

public class JBoltWechatKit {


    /**
     * 检测微信小程序系统配置
     *
     * @param application
     * @return
     */
    public static JBoltApiRet processWxaConfig(Application application) {
        // 获取application关联的小程序mpId
        Long mpId = application.getLinkTargetId();
        if (notOk(mpId)) {
            return JBoltApiRet.APP_NOT_LINK_WECHAT_XCX(application);
        }
        // 关联的小程序正确配置
        WechatMpinfo mp = JBoltWechatMpinfoCache.me.get(mpId);
        if (mp == null) {
            return JBoltApiRet.APP_NOT_LINK_WECHAT_XCX(application);
        }
        if (mp.getEnable() == null || !mp.getEnable()) {
            return JBoltApiRet.WECHAT_XCX_DISABLED(application);
        }
        // 获取微信小程序配置的APPID
        String wechatAppId = JBoltWechatConfigCache.me.getAppId(mpId);
        if (StrKit.isBlank(wechatAppId)) {
            return JBoltApiRet.WECHAT_XCX_CONFIG_ERROR(application);
        }
        // 设置到当前线程里
        JBoltApiKit.setWechatAppId(wechatAppId);
        JBoltApiKit.setWechatMpId(mpId);
        return JBoltApiRet.success();
    }

    /**
     * 检测微信公众平台（非小程序）系统配置
     *
     * @param application
     * @return
     */
    public static JBoltApiRet processWechatConfig(Application application) {
        // 获取application关联的公众平台mpId
		Long mpId = application.getLinkTargetId();
		if (notOk(mpId)) {
			return JBoltApiRet.APP_NOT_LINK_WECHAT_MP(application);
		}
		// 关联的公众平台正确配置
		WechatMpinfo mp = JBoltWechatMpinfoCache.me.get(mpId);
		if (mp == null) {
			return JBoltApiRet.APP_NOT_LINK_WECHAT_MP(application);
		}
		if (mp.getEnable() == null || !mp.getEnable()) {
			return JBoltApiRet.WECHAT_MP_DISABLED(application);
		}
		// 获取微信公众平台配置的APPID
		String wechatAppId = JBoltWechatConfigCache.me.getAppId(mpId);
		if (StrKit.isBlank(wechatAppId)) {
			return JBoltApiRet.WECHAT_MP_CONFIG_ERROR(application);
		}
		// 设置到当前线程里
		JBoltApiKit.setWechatAppId(wechatAppId);
		JBoltApiKit.setWechatMpId(mpId);
        return JBoltApiRet.success();
    }
}
